<template>
  <div v-if="isVisible" id="chatbot-window" :style="windowStyle">
    <div class="chat-header">
      <img
        class="logo"
        src="https://s21.ax1x.com/2025/03/02/pEGixnH.png"
        alt="logo"
        style="width: 32px; height: 32px"
      />

      <span class="header-title">供应链智能服务台</span>
      <button @click="reloadChat" class="top-button">
        <svg
          fill="#ffffff"
          height="18px"
          width="18px"
          version="1.1"
          id="Capa_1"
          xmlns="http://www.w3.org/2000/svg"
          xmlns:xlink="http://www.w3.org/1999/xlink"
          viewBox="0 0 489.645 489.645"
          xml:space="preserve"
          stroke="#ffffff"
        >
          <g id="SVGRepo_bgCarrier" stroke-width="0"></g>
          <g
            id="SVGRepo_tracerCarrier"
            stroke-linecap="round"
            stroke-linejoin="round"
          ></g>
          <g id="SVGRepo_iconCarrier">
            <g>
              <path
                d="M460.656,132.911c-58.7-122.1-212.2-166.5-331.8-104.1c-9.4,5.2-13.5,16.6-8.3,27c5.2,9.4,16.6,13.5,27,8.3 c99.9-52,227.4-14.9,276.7,86.3c65.4,134.3-19,236.7-87.4,274.6c-93.1,51.7-211.2,17.4-267.6-70.7l69.3,14.5 c10.4,2.1,21.8-4.2,23.9-15.6c2.1-10.4-4.2-21.8-15.6-23.9l-122.8-25c-20.6-2-25,16.6-23.9,22.9l15.6,123.8 c1,10.4,9.4,17.7,19.8,17.7c12.8,0,20.8-12.5,19.8-23.9l-6-50.5c57.4,70.8,170.3,131.2,307.4,68.2 C414.856,432.511,548.256,314.811,460.656,132.911z"
              ></path>
            </g>
          </g>
        </svg>
      </button>
    </div>
    <div class="chat-body">
      <div class="chat-message-container" ref="messageContainer">
        <MessageBubble
          v-for="message in messages"
          :key="message.id"
          :text="message.text"
          :isUser="message.isUser"
        />
      </div>
      <ChatInput
        @sendMessage="handleMessageSend"
        class="chat-input-container"
      />
    </div>
  </div>
</template>

<script>
import MessageBubble from "./MessageBubble.vue";
import ChatInput from "./ChatInput.vue";
export default {
  components: { MessageBubble, ChatInput },
  data() {
    return {
      messages: [
        { id: 1, text: "您好！请问有什么可以帮您的？", isUser: false },
      ],
      hasSent: false,
      url_config: "",
    };
  },
  props: {
    isVisible: Boolean,
    position: Object,
  },
  computed: {
    windowStyle() {
      return {
        top: `${this.position.top - 640}px`, // 40rm = 640px
        left: `${this.position.left - 384}px`, // 24rem = 384px
      };
    },
  },
  watch: {
    isVisible(newVal) {
      if (newVal) {
        this.startSendPage();
        this.url_config = this.getConfig("url_config");
      }
    },
  },
  methods: {
    getConfig(key) {
      return window.config ? window.config[key] : null;
    },
    getUrlConfig() {
      this.url_config = this.getConfig("url_config");
      if (this.url_config == null || this.url_config == "") {
        const url = prompt("请输入配置的 URL 地址", "");
        this.url_config = "http://127.0.0.1:8111/v1/navi";
      }
      return this.url_config;
    },
    startSendPage() {
      if (this.hasSent) {
        return;
      }
      this.hasSent = true;
      this.sendPageContent();
    },
    async handleMessageSend(userMessage) {
      this.messages.push({ id: Date.now(), text: userMessage, isUser: true });
      this.scrollToBottom();
      // 获取机器人回复
      await this.getBotResponse(userMessage);
    },
    reloadChat() {
      this.messages = [
        { id: 1, text: "您好！请问有什么可以帮您的？", isUser: false },
      ];
      this.scrollToBottom();
    },
    scrollToBottom() {
      this.$nextTick(() => {
        try {
          const container = this.$refs.messageContainer;
          container.scrollTop = container.scrollHeight;
        } catch (error) {
          console.error("Error:", error);
        }
      });
    },
    async sendPageContent() {
      try {
        const html_result = document.getElementsByTagName("body")[0].outerHTML;
        const url = this.getUrlConfig();
        const streamResponse = await fetch(url, {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            html: html_result,
            stream: true,
          }),
        });

        const reader = streamResponse.body.getReader();
        const decoder = new TextDecoder();
        let botMessage = { id: Date.now() + 1, text: "", isUser: false };
        this.messages.push(botMessage);
        this.scrollToBottom();
        while (true) {
          const { done, value } = await reader.read();
          if (done) {
            break;
          }
          // 解码流式数据
          const chunk = decoder.decode(value, { stream: true });
          // 解析 JSON 数据
          chunk.split("\n").forEach((line) => {
            if (line.startsWith("data: ")) {
              try {
                // 提取 JSON 部分
                const jsonString = line.slice(6).trim(); // 去掉 "data: " 前缀
                const jsonData = JSON.parse(jsonString);

                // 根据事件类型处理数据
                if (jsonData.event === "workflow_started") {
                  // 处理工作流启动的事件
                  console.log("工作流已启动，任务 ID:", jsonData.task_id);
                } else if (
                  jsonData.event === "text_chunk" &&
                  jsonData.data &&
                  jsonData.data.text
                ) {
                  // 更新等待中的 bot 消息
                  botMessage.text += jsonData.data.text;
                }
              } catch (error) {
                console.error("解析 JSON 失败:", error);
              }
            }
          });
          // 更新 UI
          const messageIndex = this.messages.findIndex(
            (msg) => msg.id === botMessage.id
          );
          if (messageIndex !== -1) {
            this.messages.pop();
            this.messages.push(botMessage);
          }
          this.scrollToBottom();
        }
      } catch (error) {
        console.error("Error:", error);
      }
    },
    async getBotResponse(userMessage) {
      try {
        // const result = document.getElementsByTagName("body")[0].outerHTML;
        const url = this.getUrlConfig();
        const streamResponse = await fetch(url, {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            html: null,
            stream: true,
            require_workflow: userMessage,
          }),
        });

        const reader = streamResponse.body.getReader();
        const decoder = new TextDecoder();
        let botMessage = { id: Date.now() + 1, text: "", isUser: false };
        this.messages.push(botMessage);
        this.scrollToBottom();
        while (true) {
          const { done, value } = await reader.read();
          if (done) {
            break;
          }
          // 解码流式数据
          const chunk = decoder.decode(value, { stream: true });
          // 解析 JSON 数据
          chunk.split("\n").forEach((line) => {
            if (line.startsWith("data: ")) {
              try {
                // 提取 JSON 部分
                const jsonString = line.slice(6).trim(); // 去掉 "data: " 前缀
                const jsonData = JSON.parse(jsonString);

                // 根据事件类型处理数据
                if (jsonData.event === "workflow_started") {
                  // 处理工作流启动的事件
                  console.log("工作流已启动，任务 ID:", jsonData.task_id);
                } else if (
                  jsonData.event === "text_chunk" &&
                  jsonData.data &&
                  jsonData.data.text
                ) {
                  // 更新等待中的 bot 消息
                  botMessage.text += jsonData.data.text;
                }
              } catch (error) {
                console.error("解析 JSON 失败:", error);
              }
            }
          });
          // 更新 UI
          const messageIndex = this.messages.findIndex(
            (msg) => msg.id === botMessage.id
          );
          if (messageIndex !== -1) {
            this.messages.pop();
            this.messages.push(botMessage);
          }
          this.scrollToBottom();
        }
      } catch (error) {
        console.error("Error:", error);
      }
    },
  },
};
</script>

<style scoped>
#chatbot-window {
  position: absolute;
  bottom: 55px;
  right: 20px;
  width: 24rem;
  height: 40rem;
  max-height: calc(100vh - 6rem);
  background-color: #ffffff;
  border-radius: 10px;
  display: flex;
  flex-direction: column;
  box-shadow: 0px 10px 30px rgba(0, 0, 0, 0.15);
  overflow: hidden;
  z-index: 9999;
  transition: transform 0.3s ease-in-out;
}
/* 头部 */
.chat-header {
  background: linear-gradient(135deg, #00c6ff, #0072ff);
  color: white;
  font-size: 20px;
  font-weight: bold;
  display: flex;
  justify-content: space-between;
  padding: 12px 20px;
  align-items: center;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transition: transform 0.2s ease, box-shadow 0.3s ease;
}

.chat-header .logo {
  width: 32px;
  height: 32px;
}

.chat-header .header-title {
  flex: 1;
  /* 居中 */
  text-align: center;
}
/* 头部刷新按钮 */
.top-button {
  background-color: transparent;
  color: white;
  border: none;
  cursor: pointer;
  font-size: 18px;
  padding-top: 2px;
}

/* 聊天内容区域 */
.chat-body {
  flex: 1;
  padding-top: 10px;
  padding-bottom: 12px;
  padding-left: 15px;
  padding-right: 7px;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  background-image: url("https://s21.ax1x.com/2025/03/02/pEGFF9f.png");
}

/* 消息容器 */
.chat-message-container {
  flex: 1;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 10px;
  position: relative; /* 用于定位滚动条 */
}

/* 隐藏滚动条 */
.chat-message-container::-webkit-scrollbar {
  width: 4px; /* 设置滚动条的宽度 */
  transition: opacity 0.3s ease; /* 添加过渡效果 */
}

.chat-message-container::-webkit-scrollbar-thumb {
  background-color: rgba(0, 0, 0, 0.3); /* 设置滚动条的颜色 */
  border-radius: 10px; /* 设置滚动条的圆角 */
}

.chat-message-container::-webkit-scrollbar-track {
  background-color: rgba(0, 0, 0, 0.1); /* 设置滚动条轨道的背景 */
}

/* 固定输入框在底部 */
.chat-input-container {
  display: flex;
  justify-content: center;
  align-items: center;
  background: white;
  width: 100%;
  box-sizing: border-box;
}

/* 悬浮效果 */
/* #chatbot-window:hover {
  transform: scale(1.02);
  box-shadow: 0px 15px 40px rgba(0, 0, 0, 0.2);
} */
.chat-widget {
  position: relative;
}
</style>
